import sys
import os

from importlib.machinery import SourceFileLoader

thisDir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(thisDir)
sys.path.append(os.path.join(thisDir, "clients"))

import PUConst
from PUHtml import PUHtml

import logging
logger = logging.getLogger(__name__)

class PU:
    def __init__(self, configPath, schemaDir):
        self.__configPath = configPath
        self.__schemaDir = schemaDir

        self.__schemaPath = os.path.join(thisDir, "PUSchema.py")
        self.__constPath = os.path.join(thisDir, "PUConst.py")

        self.__generators = {}

        self.__uiConfig = None
        self.__loadUIConfig()

    def Generate(self, client, uid, **kwargs):
        generator = self.__generators[client] if client in self.__generators else self.__createGenerator(client)
        if generator is not None:
            generator.Configure(**kwargs)
            return generator.Generate(uid)
        return None

    def __loadUIConfig(self):
        if not os.path.isdir(self.__schemaDir):
            logger.error(f"[PU] Invalid schema module dir: {self.__schemaDir}")
            exit(f"[PU] Invalid schema module dir: {self.__schemaDir}")
        checkerPath = os.path.join(self.__schemaDir, "SchemaChecker.py")
        checkerModule = SourceFileLoader("SchemaChecker", checkerPath).load_module()
        checkerClass = getattr(checkerModule, "SchemaChecker")
        checker = checkerClass(self.__configPath, self.__schemaPath, self.__constPath)
        result, self.__uiConfig = checker.Check()
        if not result:
            logger.error("UI schema check error")
            exit("UI schema check error")

    def __createGenerator(self, client):
        if client == PUConst.ClientHtml:
            self.__generators[client] = PUHtml(self.__uiConfig)
            return self.__generators[client]
        return None
